#include "Foundation.h"

#include <stdlib.h>
#include <stdio.h>



bool CFoundation::CheckEndian()
{
    const int i = 1;
    const bool bIsBigEndian = (*(char *)&i != 1);
    return bIsBigEndian;
}


unsigned int CFoundation::IPv4ToLong(const std::string strIP)
{
    // Split Ip with "."
    std::vector<std::string> vecBit = SplitString(strIP, ".");
    if(4 != vecBit.size())
    {
        return -1;
    }

    int nRet = 0;
    for(int nVecSize = 0; nVecSize < 4; nVecSize++)
    {
        // Size error
        if( 0 >= vecBit[nVecSize].size() || 3 < vecBit[nVecSize].size()) { return -1; }
        for(size_t nBitSize = 0; nBitSize < vecBit[nVecSize].size(); nBitSize++)
        {
            // Not all at number
            if('0' > vecBit[nVecSize][nBitSize] || '9' < vecBit[nVecSize][nBitSize] ) { return -1; }
        }
        nRet = nRet | atoi(vecBit[nVecSize].c_str()) << (nVecSize * 8);
    }
    return nRet;
}


std::string CFoundation::LongToIPv4(const unsigned int nIp)
{
    char cIpArray[4];
    cIpArray[0] = nIp & 0x000000ff;
    cIpArray[1] = nIp & 0x0000ff00;
    cIpArray[2] = nIp & 0x00ff0000;
    cIpArray[3] = nIp & 0xff000000;

    for(int nSize = 0; nSize < 4; nSize++)
    {
        if(0 > cIpArray[nSize] || 255 < cIpArray[nSize]) { return "-1"; }
    }
    char cIp[16];
    sprintf(cIp, "%d.%d.%d.%d", (int)cIpArray[0], (int)cIpArray[1], (int)cIpArray[2], (int)cIpArray[3]);
    return cIp;
}


std::vector<std::string> CFoundation::SplitString(const std::string strSplit, const std::string strTag)
{
    std::vector<std::string> vecSplit;
	size_t nBeginPos = 0, nEndPos = 0;
    do
    {
        nEndPos = strSplit.find(strTag, nBeginPos);
        if(std::string::npos != nEndPos)
        {
            vecSplit.push_back(strSplit.substr(nBeginPos, nEndPos - nBeginPos));
            nBeginPos = nEndPos + strTag.size();
        }
        else
        {
            vecSplit.push_back(strSplit.substr(nBeginPos));
            break;
        }
    }
    while(true);
    return vecSplit;
}


void CFoundation::TrimBothEnds(std::string strTrim, const std::string strTag, size_t nSize)
{
    size_t nBegin = 0, nEnd = strTrim.size() - 1;
	size_t nBeginFindEnd = -1, nEndFindEnd = -1;
    
    if(strTag.size() <= nSize || -1 == nSize)
    {// Erase all that find
        nBeginFindEnd = strTrim.size();
        nEndFindEnd = -1;
    }
    else
    {// Only check nSize length
        nBeginFindEnd = nSize;
        nEndFindEnd = nEnd - nSize;
    }

    // Find begin with string begin
    while((nBeginFindEnd >  nBegin ) && ( std::string::npos != strTag.find(strTrim[nBegin]) )) { nBegin++; }
    // Find end with string end
    while(( nEndFindEnd < nEnd ) && ( std::string::npos != strTag.find(strTrim[nEnd]) )) { nEnd--; }
    // Have something erase
    if(0 != nBegin && strTrim.size() - 1 != nEnd && nBegin <= nEnd) { strTrim = strTrim.substr(nBegin, nEnd - nBegin + 1); }
}
